package com.jpcc.vw.onlineRadio.adapter.item;

import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.os.RemoteException;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cns.android.atmospherelamp.AtmosphereLampManager;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.model.action.DetailItemClickAction;
import com.jpcc.vw.onlineRadio.model.action.DownloadTrackAction;
import com.jpcc.vw.onlineRadio.model.bean.RecentAlbumRadioTrackBean;
import com.jpcc.vw.onlineRadio.model.bean.Track;
import com.jpcc.vw.onlineRadio.recycle.RecyclerView.BaseItem;
import com.jpcc.vw.onlineRadio.service.AlbumRadioAudioPlayer;
import com.jpcc.vw.onlineRadio.utils.ToastUtils;
import com.jpcc.vw.onlineRadio.utils.TrackUtils;
import com.jpcc.vw.onlineRadio.widget.Indicator;
import com.liulishuo.filedownloader.FileDownloader;
import com.liulishuo.filedownloader.model.FileDownloadStatus;
import com.lzy.okhttpserver.download.DownloadInfo;
import com.lzy.okhttpserver.download.DownloadManager;
import com.orhanobut.logger.Logger;

import java.io.File;

import de.greenrobot.event.EventBus;

public class AlbumDeailItem extends BaseItem<Track> implements View.OnClickListener {

    private Track result;
    private TextView tv_item_count;
    private TextView tv_content2;
    private ImageView imv_download;
    private RelativeLayout layout_top;
    private Indicator imv_playing;
    private AnimationDrawable frameAnim;
    private ImageView imv_nonFree;

    private DownloadManager downloadManager;


    public AlbumDeailItem(ViewGroup group) {
        super(group);
    }

    @Override
    public int getRes() {
        return R.layout.adapter_album_detail_item;
    }

    @Override
    public void onCreateView(View rootView) {
        tv_item_count = (TextView) rootView.findViewById(R.id.tv_item_count);
        tv_content2 = (TextView) rootView.findViewById(R.id.tv_content2);
        imv_download = (ImageView) rootView.findViewById(R.id.imv_download);
        layout_top = (RelativeLayout) rootView.findViewById(R.id.layout_top);
//        imv_playing = (Indicator) rootView.findViewById(R.id.imv_playing);
        imv_nonFree = (ImageView) rootView.findViewById(R.id.imv_nonFree);
    }


//    private void doDownloadAnim() {
//        if (AlbumRadioAudioPlayer.get().getPlayMusic() != null) {
//            final String[] path = {TrackUtils.getTrackDir() + AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId() + AlbumRadioAudioPlayer.get().getPlayMusic().getTrackId() + "." + AlbumRadioAudioPlayer.get().getPlayMusic().getDownloadUrl().substring(AlbumRadioAudioPlayer.get().getPlayMusic().getDownloadUrl().length() - 3)};
//            if(AlbumRadioAudioPlayer.get().getPlayMusic()==null){
//                return;
//            }
//            FileDownloader.setup(getContext());
////            byte fileStatus = FileDownloader.getImpl().getStatus(AlbumRadioAudioPlayer.get().getPlayMusic().getDownloadUrl(), path[0]);
//            DownloadTrackDbBean resultQuery = null;
//            try {
//                resultQuery = DatabaseHelperOrm.getHelper(getContext()).getDownloadDao().queryBuilder().where().eq("userId", MusicApplication.GetUserId()).and().eq("albumId", AlbumRadioAudioPlayer.get().getPlayMusic().getAlbumId()).and().eq("trackId", AlbumRadioAudioPlayer.get().getPlayMusic().getTrackId()).queryForFirst();
//            } catch (SQLException e) {
//                e.printStackTrace();
//            }
//            if (resultQuery == null) {
//                frameAnim = (AnimationDrawable) getContext().getResources().getDrawable(R.drawable.animator_download);
//                imv_download.setImageDrawable(frameAnim);
//                frameAnim.start();
//            }
//        }
//        if(result!=null){
//            FileDownloader.setup(getContext());
//            frameAnim = (AnimationDrawable) getContext().getResources().getDrawable(R.drawable.animator_download);
//            imv_download.setImageDrawable(frameAnim);
//            frameAnim.start();
//        }
//    }

    @Override
    public void onBindView(Track albumDetailTrackEntity) {
        result = albumDetailTrackEntity;
        tv_item_count.setText(getPosition() + 1 + "");
//        tv_item_count.setVisibility(View.GONE);
        tv_content2.setText(result.getTrackTitle());
        if (!result.isIs_paid()) {
            imv_nonFree.setVisibility(View.GONE);
        } else {
            if (result.isIs_free()) {
                imv_nonFree.setVisibility(View.GONE);
            } else {
                imv_nonFree.setVisibility(View.VISIBLE);
            }
        }
        if ((!TextUtils.isEmpty(result.getDownloadUrl())) && (result.getDownloadUrl().length() > 5)) {
            String path_local = TrackUtils.getTrackDir() + result.getSubordinatedAlbum().getId() + result.getId() + "." + result.getDownloadUrl().substring(result.getDownloadUrl().length() - 3, result.getDownloadUrl().length());
            File file_local = new File(path_local);
//            if (file_local.exists()) {
//                imv_download.setVisibility(View.INVISIBLE);
//            } else {
//                imv_download.setVisibility(View.VISIBLE);
//            }


//            byte downloadStatus=FileDownloader.getImpl().getStatus(result.getDownloadUrl(),path_local);
////            Logger.i("downloadStatus--"+downloadStatus);
////            if(downloadStatus == FileDownloadStatus.completed){
////                imv_download.setImageResource(R.drawable.detail_success);
////                imv_download.setVisibility(View.VISIBLE);
////            }
////            else if(downloadStatus== FileDownloadStatus.started){
////                imv_download.setImageResource(R.drawable.detail_loading);
////                imv_download.setVisibility(View.VISIBLE);
////            }
////            else {
////                imv_download.setImageResource(R.drawable.detail_not_download);
////                imv_download.setVisibility(View.VISIBLE);
////            }
//            if (file_local.exists()) {
//                imv_download.setImageResource(R.drawable.detail_success);
//                imv_download.setVisibility(View.VISIBLE);
//            } else {
//                byte downloadStatus = FileDownloader.getImpl().getStatus(result.getDownloadUrl(), path_local);
//                if (downloadStatus == FileDownloadStatus.started) {
//                    imv_download.setImageResource(R.drawable.detail_loading);
//                    imv_download.setVisibility(View.VISIBLE);
//                } else {
//                    imv_download.setImageResource(R.drawable.detail_not_download);
//                    imv_download.setVisibility(View.VISIBLE);
//                }

                if (downloadManager == null) {
                    downloadManager = DownloadManager.getInstance(getContext());
                }
                DownloadInfo downloadInfo = downloadManager.getTaskByUrl(result.getDownloadUrl());
                if(downloadInfo!=null){
                    if (downloadInfo.getState() == DownloadManager.NONE) {
                        imv_download.setImageResource(R.drawable.detail_not_download);
                        imv_download.setVisibility(View.VISIBLE);
                    } else if (downloadInfo.getState() == DownloadManager.WAITING || downloadInfo.getState() == DownloadManager.DOWNLOADING) {
                        imv_download.setImageResource(R.drawable.detail_loading);
                        imv_download.setVisibility(View.VISIBLE);
                    }
                    else if(downloadInfo.getState() == DownloadManager.FINISH){
                        imv_download.setImageResource(R.drawable.detail_success);
                        imv_download.setVisibility(View.VISIBLE);
                    }
                }

//            }
        } else {
            imv_download.setVisibility(View.VISIBLE);
        }


        imv_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (result.isCanDownload() && !TextUtils.isEmpty(result.getDownloadUrl())) {
                    String path = TrackUtils.getTrackDir() + result.getSubordinatedAlbum().getId() + result.getId() + "." + result.getDownloadUrl().substring(result.getDownloadUrl().length() - 3, result.getDownloadUrl().length());
                    File file = new File(path);
                    Logger.i("path-->" + path);
//                    if (file.exists()) {
//                        ToastUtils.show(R.string.string_43);
//                        return;
//                    }
                    DownloadTrackAction action = new DownloadTrackAction();
                    action.setTrack(result);
                    action.setDir(TrackUtils.getTrackDir());
                    action.setFileName(result.getSubordinatedAlbum().getId() + "" + result.getId() + "." + result.getDownloadUrl().substring(result.getDownloadUrl().length() - 3));
                    EventBus.getDefault().post(action);
//                    imv_download.setImageResource(R.drawable.detail_loading);
//                    doDownloadAnim();
                } else {
                    ToastUtils.show(R.string.string_95);
                }


            }
        });


        String bgColor = "#404040";
        if (Constants.isRelease) {
            try {
                boolean atmosphereStatus = AtmosphereLampManager.getInstance(getContext()).isHmiAtmosphereLampOn();
                String color = AtmosphereLampManager.getInstance(getContext()).getAtmosphereLampColor();
                if (atmosphereStatus) {
                    if (!TextUtils.isEmpty(color)) {
                        bgColor = color;
                    }
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }


        if (AlbumRadioAudioPlayer.get().getPlayMusic() != null) {
            RecentAlbumRadioTrackBean lastAlbum = AlbumRadioAudioPlayer.get().getPlayMusic();
            if (result.getId() == lastAlbum.getTrackId()) {
//                layout_top.setBackgroundColor(Color.parseColor(bgColor));
                layout_top.setBackgroundColor(Color.parseColor("#000000"));
                imv_playing.setVisibility(View.VISIBLE);
            } else {
                layout_top.setBackgroundColor(Color.parseColor("#000000"));
                imv_playing.setVisibility(View.GONE);
            }
        } else {
            layout_top.setBackgroundColor(Color.parseColor("#000000"));
            imv_playing.setVisibility(View.GONE);
        }

        if (AlbumRadioAudioPlayer.get().isPlaying() || AlbumRadioAudioPlayer.get().isPreparing()) {
            imv_playing.setIndicatorPause(true);
        } else {
            imv_playing.setIndicatorPause(false);
        }
    }

    @Override
    public void onClick(View v) {
        DetailItemClickAction action = new DetailItemClickAction();
        action.setPosition(getPosition());
        EventBus.getDefault().post(action);
        imv_playing.setIndicatorPause(true);
    }
}
